﻿using System;
using log4net;
using MyMessages;
using NServiceBus;
using NHibernate;

namespace Subscriber1
{
    public class RefreshSagaHandler : IHandleMessages<RefreshSagaMessage>, IDisposable
    {
        private readonly IBus bus;
        private readonly ISessionFactory factory;

        public RefreshSagaHandler(IBus bus, ISessionFactory factory)
        {
            this.bus = bus;
            this.factory = factory;
        }

        public void Handle(RefreshSagaMessage message)
        {
            using (var session = factory.OpenSession())
            {
                var sqlQuery = session.CreateSQLQuery("TRUNCATE TABLE SagaHeader");
                sqlQuery.UniqueResult();

                sqlQuery = session.CreateSQLQuery("TRUNCATE TABLE SagaUpdates");
                sqlQuery.UniqueResult();
            }

            Logger.Info(string.Format("Subscriber 1 received a Refresh Saga Message and truncated the MySagaData and SomeMoreSagaData"));
            Console.WriteLine("==========================================================================");
        }

        private static readonly ILog Logger = LogManager.GetLogger(typeof(RefreshSagaHandler));

        #region IDisposable Members

        public void Dispose()
        {
        }

        #endregion
    }
}
